﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace Esponce.Converters
{
	public class VisibilityConverter : IValueConverter
	{
		#region IValueConverter members
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			Visibility visibility = Visibility.Visible;
			if (value != null && value is bool)
			{
				#region Boolean
				bool p = (bool)value;
				if (parameter is string && (string)parameter == "Invert")
				{
					p = !p;
				}
				visibility = (p ? Visibility.Visible : Visibility.Collapsed);
				#endregion
			}
			else if (value is string)
			{
				#region String
				//Hide if string is null or empty
				string s = value as string;
				bool p = !string.IsNullOrEmpty(s);
				if (parameter is string && (string)parameter == "Invert")
				{
					p = !p;
				}
				visibility = (p ? Visibility.Visible : Visibility.Collapsed);
				#endregion
			}
			else if (value != null && typeof(Enum).IsAssignableFrom(value.GetType())) //If value is enum
			{
				string p = parameter as string;
				if (!string.IsNullOrEmpty(p) && (p.Contains(",") || p.Contains("|")))
				{
					var parts = p.Split(new char[] { ',', '|' });
					visibility = Visibility.Collapsed;
					foreach (string part in parts)
					{
						if (part == value.ToString())
						{
							visibility = Visibility.Visible;
							break;
						}
					}
				}
				else
				{
					visibility = (p == value.ToString() ? Visibility.Visible : Visibility.Collapsed);
				}
			}
			return visibility;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			bool result = false;
			if (value != null && value is Visibility)
			{
				Visibility p = (Visibility)parameter;
				result = (p == Visibility.Visible);
				if (parameter is string && (string)parameter == "Invert")
				{
					result = !result;
				}
			}
			return result;
		}
		#endregion
	}
}
